import dash
from dash import html, Input, Output, dcc
import feffery_antd_components as fac
from urllib import parse

app = dash.Dash(__name__, update_title=None)

app.layout = html.Div(
    [
        dcc.Location(id='url'),
        html.Div(
            fac.AntdBreadcrumb(
                id='bread-crumb-demo',
                items=[
                    {
                        'title': '首页',
                        'href': '/',
                        'icon': 'antd-home'
                    }
                ]
            ),
            style={
                'padding': '50px'
            }
        ),
        html.Div(
            id='query-text-demo',
            style={
                'padding': '0 50px'
            }
        )
    ]
)


@app.callback(
    Output('bread-crumb-demo', 'items'),
    [
        Input('url', 'pathname'),
        Input('bread-crumb-demo', 'items')
    ]
)
def router(pathname: str, items: list):
    new_items = [items[0]]

    if pathname == '/':
        return dash.no_update

    url_level = pathname.split('/')
    url_level.remove('')

    new_items.extend(
        {
            'title': item,
            'href': f'/{item}'
        }
        for item in url_level
    )

    return new_items


@app.callback(
    Output('query-text-demo', 'children'),
    Input('url', 'search')
)
def show_query_text(search):
    if not search:
        return dash.no_update
    query_params = {
        key: value[0]
        for key, value in parse.parse_qs(search.split('?')[1]).items()
    }
    return fac.AntdText(
        f'''{query_params}''',
        code=True
    )


if __name__ == '__main__':
    app.run_server(debug=True)
